<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types=1);

namespace app\busine\controller;

use app\base\BaseController;
use app\busine\model\LicenseOutside;
use app\busine\model\LicensePayment;
use app\license\model\License;
use app\license\model\LicenseCert;
use think\facade\Db;
use think\facade\View;

class Index extends BaseController
{

    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            $whereOr = array();
            if (!empty($param['keywords'])) {
                $where[] = ['a.license_name', 'like', '%' . $param['keywords'] . '%'];
            }
            if ($this->uid != 1 && $this->uid != 3) {
                $where[] = ['a.admin_id', '=', $this->uid];
            }
            $where[] = ['a.sign_state', '=', 0];
            $where[] = ['a.delete_time', '=', 0];
            $model = new LicenseCert();
            $list = $model->get_list($param, $where, $whereOr);
            return table_assign(0, '', $list);
        } else {

            return view();
        }
    }

    //添加&&编辑
    public function add()
    {
        $param = get_params();
        unset($param['file']);
        unset($param['scene']);
        if (request()->isAjax()) {
            $check_crets = $param['check_crets'] ?? [];
            if (empty($check_crets)) {
                return to_assign(1, '请先保存资质类型');
            }
            unset($param['check_crets']);
            $param['admin_id'] = $this->uid;
            if (!empty($param['id']) && $param['id'] > 0) {
                $param['update_time'] = time();
                $res = Db::name('license_cert')->where(['id' => $param['id']])->update($param);
                if ($res) {
                    Db::name('license_cert_cates')->where('cert_id', $param['id'])->delete();
                    if (!empty($check_crets)) {
                        $certs_all = [];
                        foreach ($check_crets as $k => $v) {
                            $certs = [];
                            list($a, $b, $c, $d) = explode('|', $v);
                            $certs['cert_serial'] = $a;
                            $certs['cert_from'] = $b;
                            $certs['cert_level'] = $c;
                            $certs['cert_from_type'] = $d;
                            $certs['cert_id'] = $param['id'];
                            $certs_all[] = $certs;
                        }
                        Db::name('license_cert_cates')->insertAll($certs_all);
                    }

                    add_log('edit', $param['id'], $param);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            } else {
                $param['create_time'] = time();
                $param['admin_id'] = $this->uid;
                $aid = Db::name('license_cert')->insertGetId($param);
                if ($aid) {
                    if (!empty($check_crets)) {
                        $certs_all = [];
                        foreach ($check_crets as $k => $v) {
                            $certs = [];
                            list($a, $b, $c, $d) = explode('|', $v);
                            $certs['cert_serial'] = $a;
                            $certs['cert_from'] = $b;
                            $certs['cert_level'] = $c;
                            $certs['cert_from_type'] = $d;
                            $certs['cert_id'] = $aid;
                            $certs_all[] = $certs;
                        }
                        Db::name('license_cert_cates')->insertAll($certs_all);
                    }
                    add_log('add', $aid, $param);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            $cert_id = isset($param['cert_id']) ? $param['cert_id'] : 0;
            View::assign('cert_id', $cert_id);
            if ($id > 0) {
                $model = new LicenseCert();
                $detail = $model->detail($id);
                $detail->cert_cates = Db::name('license_cert_cates')->where('cert_id', $id)->select()->toArray();
                View::assign('detail', $detail);
            }
            return view();
        }
    }

    //删除
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $data['id'] = $id;
            $data['delete_time'] = time();
            if (Db::name('license_cert')->update($data) !== false) {
                add_log('delete', $id);
                Db::name('Approve')->where('type',26)->where('action_id',$id)->delete();
                return to_assign(0, "删除成功");
            } else {
                return to_assign(1, "删除失败");
            }
        } else {
            return to_assign(1, "错误的请求");
        }
    }


    public function report()
    {
        $param = get_params();

        if (request()->isAjax()) {
            $param['check_status'] = 1;
            $param['check_step_sort'] = 0;
            $flow_list = Db::name('Flow')->where('id', $param['flow_id'])->value('flow_list');
            $flow = unserialize($flow_list);
            //删除原来的审核流程和审核记录
            Db::name('FlowStep')->where(['action_id' => $param['id'], 'type' => 9, 'delete_time' => 0])->update(['delete_time' => time()]);
            Db::name('FlowRecord')->where(['action_id' => $param['id'], 'type' => 9, 'delete_time' => 0])->update(['delete_time' => time()]);
            if (!isset($param['check_admin_ids'])) {
                if ($flow[0]['flow_type'] == 1) {
                    //部门负责人
                    $leader = get_department_leader($this->uid);
                    if ($leader == 0) {
                        return to_assign(1, '审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                    } else {
                        $param['check_admin_ids'] = $leader;
                    }
                } else if ($flow[0]['flow_type'] == 2) {
                    //上级部门负责人
                    $leader = get_department_leader($this->uid, 1);
                    if ($leader == 0) {
                        return to_assign(1, '审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                    } else {
                        $param['check_admin_ids'] = $leader;
                    }
                } else {
                    $param['check_admin_ids'] = $flow[0]['flow_uids'];
                }
                foreach ($flow as $key => &$value) {
                    $value['action_id'] = $param['id'];
                    $value['sort'] = $key;
                    $value['type'] = 9;
                    $value['create_time'] = time();
                }
                //增加审核流程
                Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
            } else {
                $flow_step = array(
                    'action_id' => $param['id'],
                    'type' => 9,
                    'flow_uids' => $param['check_admin_ids'],
                    'create_time' => time()
                );
                //增加审核流程
                Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
            }

            $res = LicenseCert::where('id', $param['id'])->strict(false)->field(true)->update($param);
            if ($res !== false) {
                $appro['action_id'] = $param['id'];
                $appro['type'] = 26;
                $appro['start_time'] = time();
                $appro['admin_id'] = $this->uid;
                $appro['department_id'] = $this->did;
                $appro['create_time'] = time();
                $appro['flow_id'] =  $param['flow_id'];
                $appro['check_admin_ids'] = $param['check_admin_ids'];
                $appro['copy_uids'] = $param['copy_uids'];
                $appro['check_status'] = $param['check_status'];
                if(empty(Db::name('Approve')->where('action_id', $appro['action_id'])->where('type',$appro['type'])->find())){
                    Db::name('Approve')->strict(false)->field(true)->insertGetId($appro);
                }else{
                    Db::name('Approve')->where('action_id', $appro['action_id'])->where('type',$appro['type'])->strict(false)->field(true)->update($appro);
                }
                //添加提交申请记录
                $checkData = array(
                    'action_id' => $param['id'],
                    'check_user_id' => $this->uid,
                    'content' => '重新提交申请',
                    'type' => 9,
                    'check_time' => time(),
                    'create_time' => time()
                );
                $record_id = Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
                add_log('edit', $param['id'], $param);
                //发送消息通知
                $msg = [
                    'from_uid' => $this->uid,
                    'title' => '业务-新办',
                    'action_id' => $param['id']
                ];
                $users = $param['check_admin_ids'];
                sendMessage($users, 101, $msg);
                return to_assign();
            } else {
                return to_assign(1, '操作失败');
            }
        } else {


            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            $department = $this->did;
            //获取发票审批流程
            $flows = get_type_department_flows(9, $department);
            View::assign('user', get_admin($this->uid));
            View::assign('flows', $flows);
            if ($id > 0) {
                $model = new LicenseCert();
                $detail = $model->detail($id);
                View::assign('detail', $detail);
            }
            return view();
        }
    }


    //查看
    public function view()
    {
        $param = get_params();

        if (request()->isAjax()) {

        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            if ($id > 0) {
                $model = new LicenseCert();
                $detail = $model->detail($id);

                $certs = Db::name('license_cert_cates')->whereIn('cert_id', $id)->select()->toArray();
                $str = '';
                $str = '';
                $cert_types = [];
                foreach ($certs as $k => $v) {
                    if ($str == '') {
                        $str .= $v['cert_serial'] . '-' . $v['cert_from'] . '-' . $v['cert_level'];
                    } else {
                        $str .= '|' . $v['cert_serial'] . '-' . $v['cert_from'] . '-' . $v['cert_level'];
                    }
                    $cert_types[] = $v['cert_from_type'];
                }
                $cert_types = implode('|', array_unique($cert_types));
                $detail->cert_types = $cert_types;
                $detail->projects = $str;
                View::assign('detail', $detail);

                $flows = Db::name('FlowStep')->where(['action_id' => $detail['id'], 'type' => 9, 'sort' => $detail['check_step_sort'], 'delete_time' => 0])->find();
                $detail['check_user'] = '-';
                $detail['copy_user'] = '-';
                $check_user_ids = [];
                if ($detail['check_status'] == 1) {
                    if ($flows['flow_type'] == 1) {
                        $detail['check_user'] = '部门负责人';
                        $check_user_ids[] = get_department_leader($detail['admin_id']);
                    } else if ($flows['flow_type'] == 2) {
                        $detail['check_user'] = '上级部门负责人';
                        $check_user_ids[] = get_department_leader($detail['admin_id'], 1);
                    } else {
                        $check_user_ids = explode(',', $flows['flow_uids']);
                        $check_user = Db::name('Admin')->where('id', 'in', $flows['flow_uids'])->column('name');
                        $detail['check_user'] = implode(',', $check_user);
                    }
                }

                if ($detail['copy_uids'] != '') {
                    $copy_user = Db::name('Admin')->where('id', 'in', $detail['copy_uids'])->column('name');
                    $detail['copy_user'] = implode(',', $copy_user);
                }
                $is_check_admin = 0;
                $is_create_admin = 0;
                if ($detail['admin_id'] == $this->uid) {
                    $is_create_admin = 1;
                }
                if (in_array($this->uid, $check_user_ids)) {
                    $is_check_admin = 1;
                    //当前审核节点详情
                    if ($flows['flow_type'] == 4) {
                        $check_count = Db::name('FlowRecord')->where(['action_id' => $detail['id'], 'type' => 9, 'step_id' => $flows['id'], 'check_user_id' => $this->uid])->count();
                        if ($check_count > 0) {
                            $is_check_admin = 0;
                        }
                    }
                }

                $check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
                    ->alias('f')
                    ->join('Admin a', 'a.id = f.check_user_id', 'left')
                    ->where(['f.action_id' => $detail['id'], 'f.type' => 9])
                    ->order('check_time desc')
                    ->select()->toArray();
                foreach ($check_record as $kk => &$vv) {
                    $vv['check_time_str'] = date('Y-m-d H:i', $vv['check_time']);
                    $vv['status_str'] = '提交';
                    if ($vv['status'] == 1) {
                        $vv['status_str'] = '审核通过';
                    } else if ($vv['status'] == 2) {
                        $vv['status_str'] = '审核拒绝';
                    }
                    if ($vv['status'] == 3) {
                        $vv['status_str'] = '撤销';
                    }
                }

                View::assign('is_create_admin', $is_create_admin);
                View::assign('is_check_admin', $is_check_admin);
                View::assign('check_record', $check_record);
                View::assign('flows', $flows);
                View::assign('uid', $this->uid);
            }
            return view();
        }
    }

    public function payment()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $cert_id = isset($param['cert_id']) ? $param['cert_id'] : 0;
            if ($cert_id == 0) {
                return to_assign(1, "缺少参数");
            }
            $where = array();
            $where[] = ['a.delete_time', '=', 0];
            $where[] = ['a.cert_id', '=', $cert_id];
            $whereOr = [];

            $model = new LicensePayment();
            $list = $model->get_list($param, $where, $whereOr);

            return table_assign(0, '', $list);
        } else {
            $param = get_params();
            $cert_id = isset($param['cert_id']) ? $param['cert_id'] : 0;
            View::assign('cert_id', $cert_id);
            return view();
        }

    }

    //添加&&编辑
    public function payment_add()
    {
        $param = get_params();
        unset($param['file']);
        unset($param['scene']);
        if (empty($param['money_date'])) {
            unset($param['money_date']);
        }
        if (request()->isAjax()) {
            if ($param['account_status'] == 1){
                if(!isset($param['deduct'])||$param['deduct']==''){
                    return to_assign(1, '收款已结清必须填写提成金额');
                }
                LicenseCert::where('id',$param['cert_id'])->update(['deduct'=>$param['deduct']]);
            }
            $param['check_status'] = 1;
            $param['check_step_sort'] = 0;
            $flow_list = Db::name('Flow')->where('id', $param['flow_id'])->value('flow_list');
            $flow = unserialize($flow_list);

            //删除原来的审核流程和审核记录
            Db::name('FlowStep')->where(['action_id' => $param['id'], 'type' => 10, 'delete_time' => 0])->update(['delete_time' => time()]);
            Db::name('FlowRecord')->where(['action_id' => $param['id'], 'type' => 10, 'delete_time' => 0])->update(['delete_time' => time()]);

            $licence = Db::name('license_cert')->where('id', $param['cert_id'])->find();
            $param['license_name'] = $licence['license_name'];
            $param['license_id'] = $licence['license_id'];
            if (!empty($param['id']) && $param['id'] > 0) {
                $param['update_time'] = time();

                if (!isset($param['check_admin_ids'])) {
                    if ($flow[0]['flow_type'] == 1) {
                        //部门负责人
                        $leader = get_department_leader($this->uid);
                        if ($leader == 0) {
                            return to_assign(1, '审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                        } else {
                            $param['check_admin_ids'] = $leader;
                        }
                    } else if ($flow[0]['flow_type'] == 2) {
                        //上级部门负责人
                        $leader = get_department_leader($this->uid, 1);
                        if ($leader == 0) {
                            return to_assign(1, '审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                        } else {
                            $param['check_admin_ids'] = $leader;
                        }
                    } else {
                        $param['check_admin_ids'] = $flow[0]['flow_uids'];
                    }
                    foreach ($flow as $key => &$value) {
                        $value['action_id'] = $param['id'];
                        $value['sort'] = $key;
                        $value['type'] = 10;
                        $value['create_time'] = time();
                    }
                    //增加审核流程
                    Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
                } else {
                    $flow_step = array(
                        'action_id' => $param['id'],
                        'type' => 10,
                        'flow_uids' => $param['check_admin_ids'],
                        'create_time' => time()
                    );
                    //增加审核流程
                    Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
                }
                $model = new LicensePayment();
                $exid = $model->strict(false)->field(true)->update($param);
                if ($exid) {
                    //添加提交申请记录
                    $checkData = array(
                        'action_id' => $param['id'],
                        'check_user_id' => $this->uid,
                        'content' => '重新提交申请',
                        'type' => 10,
                        'check_time' => time(),
                        'create_time' => time()
                    );
                    $record_id = Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
                    add_log('edit', $param['id'], $param);
                    //发送消息通知
                    $msg = [
                        'from_uid' => $this->uid,
                        'title' => '业务-新办收款',
                        'action_id' => $param['id']
                    ];
                    $users = $param['check_admin_ids'];
                    sendMessage($users, 111, $msg);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            } else {
                $param['create_time'] = time();
                $param['admin_id'] = $this->uid;

                if (!isset($param['check_admin_ids'])) {
                    if ($flow[0]['flow_type'] == 1) {
                        //部门负责人
                        $leader = get_department_leader($this->uid);
                        if ($leader == 0) {
                            return to_assign(1, '审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                        } else {
                            $param['check_admin_ids'] = $leader;
                        }
                    } else if ($flow[0]['flow_type'] == 2) {
                        //上级部门负责人
                        $leader = get_department_leader($this->uid, 1);
                        if ($leader == 0) {
                            return to_assign(1, '审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                        } else {
                            $param['check_admin_ids'] = $leader;
                        }
                    } else {
                        $param['check_admin_ids'] = $flow[0]['flow_uids'];
                    }
                    $model = new LicensePayment();
                    $exid = $model->field(true)->insertGetId($param);
                    foreach ($flow as $key => &$value) {
                        $value['action_id'] = $exid;
                        $value['sort'] = $key;
                        $value['type'] = 10;
                        $value['create_time'] = time();
                    }
                    //增加审核流程
                    Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
                } else {
                    $model = new LicensePayment();
                    $exid = $model->strict(false)->field(true)->insertGetId($param);
                    $flow_step = array(
                        'action_id' => $exid,
                        'type' => 10,
                        'flow_uids' => $param['check_admin_ids'],
                        'create_time' => time()
                    );
                    //增加审核流程
                    Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
                }
                if ($exid) {
                    $appro['action_id'] = $exid;
                    $appro['type'] = 27;
                    $appro['start_time'] = time();
                    $appro['admin_id'] = $this->uid;
                    $appro['department_id'] = $this->did;
                    $appro['create_time'] = time();
                    $appro['flow_id'] =  $param['flow_id'];
                    $appro['check_admin_ids'] = $param['check_admin_ids'];
                    $appro['copy_uids'] = $param['copy_uids'];
                    $appro['check_status'] = $param['check_status'];
                     Db::name('Approve')->strict(false)->field(true)->insertGetId($appro);

                    //添加提交申请记录
                    $checkData = array(
                        'action_id' => $exid,
                        'check_user_id' => $this->uid,
                        'content' => '提交申请',
                        'type' => 10,
                        'check_time' => time(),
                        'create_time' => time()
                    );
                    $record_id = Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
                    add_log('apply', $exid, $param);
                    //发送消息通知
                    $msg = [
                        'from_uid' => $this->uid,
                        'title' => '业务-新办收款',
                        'action_id' => $exid
                    ];
                    $users = $param['check_admin_ids'];
                    sendMessage($users, 111, $msg);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            }

        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            $cert_id = isset($param['cert_id']) ? $param['cert_id'] : 0;
            View::assign('cert_id', $cert_id);
            if ($id > 0) {
                $model = new LicensePayment();
                $detail = $model->detail($id);
                View::assign('detail', $detail);
            }
            $department = $this->did;
            //获取发票审批流程
            $flows = get_type_department_flows(10, $department);
            View::assign('user', get_admin($this->uid));
            View::assign('flows', $flows);
            return view();
        }
    }

    //添加&&编辑
    public function payment_view()
    {
        $param = get_params();
        $id = isset($param['id']) ? $param['id'] : 0;
        View::assign('id', $id);
        $model = new LicensePayment();
        $detail = $model->detail($id);
        View::assign('detail', $detail);

        $flows = Db::name('FlowStep')->where(['action_id' => $detail['id'], 'type' => 10, 'sort' => $detail['check_step_sort'], 'delete_time' => 0])->find();
        $detail['check_user'] = '-';
        $detail['copy_user'] = '-';
        $check_user_ids = [];
        if ($detail['check_status'] == 1) {
            if ($flows['flow_type'] == 1) {
                $detail['check_user'] = '部门负责人';
                $check_user_ids[] = get_department_leader($detail['admin_id']);
            } else if ($flows['flow_type'] == 2) {
                $detail['check_user'] = '上级部门负责人';
                $check_user_ids[] = get_department_leader($detail['admin_id'], 1);
            } else {
                $check_user_ids = explode(',', $flows['flow_uids']);
                $check_user = Db::name('Admin')->where('id', 'in', $flows['flow_uids'])->column('name');
                $detail['check_user'] = implode(',', $check_user);
            }
        }

        if ($detail['copy_uids'] != '') {
            $copy_user = Db::name('Admin')->where('id', 'in', $detail['copy_uids'])->column('name');
            $detail['copy_user'] = implode(',', $copy_user);
        }

        $is_check_admin = 0;
        $is_create_admin = 0;
        if ($detail['admin_id'] == $this->uid) {
            $is_create_admin = 1;
        }
        if (in_array($this->uid, $check_user_ids)) {
            $is_check_admin = 1;
            //当前审核节点详情
            if ($flows['flow_type'] == 4) {
                $check_count = Db::name('FlowRecord')->where(['action_id' => $detail['id'], 'type' => 10, 'step_id' => $flows['id'], 'check_user_id' => $this->uid])->count();
                if ($check_count > 0) {
                    $is_check_admin = 0;
                }
            }
        }

        $check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
            ->alias('f')
            ->join('Admin a', 'a.id = f.check_user_id', 'left')
            ->where(['f.action_id' => $detail['id'], 'f.type' => 10])
            ->order('check_time desc')
            ->select()->toArray();
        foreach ($check_record as $kk => &$vv) {
            $vv['check_time_str'] = date('Y-m-d H:i', $vv['check_time']);
            $vv['status_str'] = '提交';
            if ($vv['status'] == 1) {
                $vv['status_str'] = '审核通过';
            } else if ($vv['status'] == 2) {
                $vv['status_str'] = '审核拒绝';
            }
            if ($vv['status'] == 3) {
                $vv['status_str'] = '撤销';
            }
        }

        View::assign('is_create_admin', $is_create_admin);
        View::assign('is_check_admin', $is_check_admin);
        View::assign('check_record', $check_record);
        View::assign('flows', $flows);
        View::assign('uid', $this->uid);

        $model = new LicenseCert();
        $cert_detail = $model->detail($detail->cert_id);
        $certs = Db::name('license_cert_cates')->whereIn('cert_id', $detail->cert_id)->select()->toArray();
        $str = '';
        $cert_types = [];
        foreach ($certs as $k => $v) {
            if ($str == '') {
                $str .= $v['cert_serial'] . '-' . $v['cert_from'] . '-' . $v['cert_level'];
            } else {
                $str .= '|' . $v['cert_serial'] . '-' . $v['cert_from'] . '-' . $v['cert_level'];
            }
            $cert_types[] = $v['cert_from_type'];
        }
        $cert_types = implode('|', array_unique($cert_types));
        $cert_detail->cert_types = $cert_types;
        $cert_detail->projects = $str;
        View::assign('cert_info', $cert_detail);


        return view();
    }

//删除
    public function payment_delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $data['id'] = $id;
            $data['delete_time'] = time();
            if (Db::name('license_payment')->update($data) !== false) {
                add_log('delete', $id);
                Db::name('Approve')->where('type',27)->where('action_id',$id)->delete();
                return to_assign(0, "删除成功");
            } else {
                return to_assign(1, "删除失败");
            }
        } else {
            return to_assign(1, "错误的请求");
        }
    }

}
